export function getClosestPoint(val, { marks = [], step, min, max }) {
  const points = Object.keys(marks).map(parseFloat)
  if (step != null) {
    const decimals = `${step}`.split('.')[1]?.length || 0
    // toFixed解决精度问题
    points.push(+(Math.round((val - min) / step) * step + min).toFixed(decimals))
  }
  const diffs = points.map(p => Math.abs(val - p))
  return points[diffs.indexOf(Math.min(...diffs))]
}

export function ensureValueInRange(val, { min ,max }) {
  return Math.min(max, Math.max(min, val))
}

export function ensureValuePrecision(val, props) {
  return getClosestPoint(val, props)
}

export function generateTrack({ step, marks, min, max }) {
  let arr = Array(max-min)
  for (let i = min; i <= max; i += step) {
    arr[i - min] = i
  }
  if (arr[arr.length-1] != max) {
    arr[arr.length-1] = max
  }
  Object.keys(marks || {}).forEach(p => {
    arr[+p - min] = +p
  })
  return arr.filter(p => p != null)
}